<template>
  <div class="karma-page">
    <!-- 页面标题 -->
    <div class="ancient-title">因果业力系统</div>

    <!-- 统计概览 -->
    <a-row :gutter="[24, 24]" class="stats-row">
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="总记录数" :value="totalKarmaCount" :value-style="{ color: '#d4990a', fontSize: '24px' }" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="善行记录" :value="goodDeedsCount" :value-style="{ color: '#52c41a', fontSize: '24px' }" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="恶行记录" :value="badDeedsCount" :value-style="{ color: '#fa541c', fontSize: '24px' }" />
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic title="业力等级分布" :value="karmaByPerson.length" suffix="人" :value-style="{ color: '#722ed1', fontSize: '24px' }" />
        </a-card>
      </a-col>
    </a-row>

    <!-- 功能导航卡片 -->
    <a-row :gutter="[24, 24]" class="navigation-row">
      <a-col :xs="24" :sm="8">
        <a-card hoverable class="nav-card good-deeds-card" @click="navigateToGoodDeeds">
          <template #cover>
            <div class="nav-card-icon good-deeds-icon">
              <SmileOutlined style="font-size: 48px" />
            </div>
          </template>
          <a-card-meta title="善行记录管理" description="管理善行类型分类、时间地点、受益人信息和影响评估" />
          <div class="nav-card-stats">
            <a-space>
              <span>善行记录: {{ goodDeedsCount }}</span>
              <span>积分: +{{ totalGoodScore }}</span>
            </a-space>
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="8">
        <a-card hoverable class="nav-card bad-deeds-card" @click="navigateToBadDeeds">
          <template #cover>
            <div class="nav-card-icon bad-deeds-icon">
              <FrownOutlined style="font-size: 48px" />
            </div>
          </template>
          <a-card-meta title="恶行记录管理" description="管理恶行等级分类、犯罪记录、受害者信息和后果追踪" />
          <div class="nav-card-stats">
            <a-space>
              <span>恶行记录: {{ badDeedsCount }}</span>
              <span>罪孽: {{ totalBadScore }}</span>
            </a-space>
          </div>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="8">
        <a-card hoverable class="nav-card engine-card" @click="navigateToEngine">
          <template #cover>
            <div class="nav-card-icon engine-icon">
              <ThunderboltOutlined style="font-size: 48px" />
            </div>
          </template>
          <a-card-meta title="业力计算引擎" description="业力积分规则、善恶抵消计算、趋势分析和报应预测" />
          <div class="nav-card-stats">
            <a-space>
              <span>规则数: {{ activeRulesCount }}</span>
              <span>预测: {{ pendingRetributionCount }}人</span>
            </a-space>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 操作栏 -->
    <a-card :bordered="false" class="action-card">
      <a-row :gutter="[16, 16]" align="middle">
        <a-col :xs="24" :sm="8">
          <a-input-search v-model:value="searchQuery" placeholder="搜索人员姓名" @search="handleSearch" />
        </a-col>
        <a-col :xs="24" :sm="6">
          <a-select v-model:value="typeFilter" placeholder="类型筛选" @change="handleFilterChange">
            <a-select-option value="all">全部类型</a-select-option>
            <a-select-option value="goodDeed">善行</a-select-option>
            <a-select-option value="badDeed">恶行</a-select-option>
          </a-select>
        </a-col>
        <a-col :xs="24" :sm="4">
          <a-button type="primary" @click="showAddModal = true">
            <PlusOutlined />
            添加记录
          </a-button>
        </a-col>
        <a-col :xs="24" :sm="3">
          <a-button @click="showPersonModal = true">
            <UserOutlined />
            业力排行
          </a-button>
        </a-col>
        <a-col :xs="24" :sm="3">
          <a-button @click="showStatisticsModal = true">
            <BarChartOutlined />
            数据分析
          </a-button>
        </a-col>
      </a-row>
    </a-card>

    <!-- 业力记录列表 -->
    <a-card title="业力记录" :bordered="false" class="records-card">
      <a-table :columns="columns" :data-source="karmaRecords" :loading="loading" row-key="id" :pagination="{ pageSize: 10 }">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <a-tag :color="record.type === 'goodDeed' ? 'green' : 'red'">
              {{ record.type === 'goodDeed' ? '善行' : '恶行' }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'score'">
            <span :class="['score-value', record.score > 0 ? 'positive' : 'negative']"> {{ record.score > 0 ? '+' : '' }}{{ record.score }} </span>
          </template>

          <template v-else-if="column.key === 'action'">
            <a-tag color="blue">
              {{ getActionName(record.type, record.action) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'actions'">
            <a-space>
              <a-button type="link" size="small" @click="viewRecord(record)"> 查看详情 </a-button>
              <a-button type="link" size="small" @click="editRecord(record)"> 编辑 </a-button>
              <a-button type="link" size="small" danger @click="deleteRecord(record)"> 删除 </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑记录弹窗 -->
    <a-modal v-model:open="showAddModal" :title="editingRecord ? '编辑业力记录' : '添加业力记录'" @ok="handleSaveRecord" @cancel="handleCancelEdit">
      <a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
        <a-form-item label="人员姓名" name="personName">
          <a-input v-model:value="formData.personName" placeholder="请输入人员姓名" />
        </a-form-item>

        <a-form-item label="行为类型" name="type">
          <a-radio-group v-model:value="formData.type" @change="handleTypeChange">
            <a-radio value="goodDeed">善行</a-radio>
            <a-radio value="badDeed">恶行</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="具体行为" name="action">
          <a-select v-model:value="formData.action" placeholder="请选择具体行为">
            <a-select-option v-for="(rule, key) in currentActionRules" :key="key" :value="key"> {{ rule.name }} ({{ rule.score > 0 ? '+' : '' }}{{ rule.score }}分) </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="行为描述" name="description">
          <a-textarea v-model:value="formData.description" placeholder="请详细描述该行为" :rows="3" />
        </a-form-item>

        <a-form-item label="发生地点" name="location">
          <a-input v-model:value="formData.location" placeholder="请输入发生地点" />
        </a-form-item>

        <a-form-item label="见证人" name="witnesses">
          <a-select v-model:value="formData.witnesses" mode="tags" placeholder="请输入见证人姓名" style="width: 100%" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 业力排行弹窗 -->
    <a-modal v-model:open="showPersonModal" title="业力排行榜" :width="800" :footer="null">
      <a-list :data-source="karmaByPerson" :pagination="{ pageSize: 5 }">
        <template #renderItem="{ item, index }">
          <a-list-item>
            <a-list-item-meta>
              <template #avatar>
                <a-avatar :style="{ backgroundColor: getKarmaLevel(item.totalScore).color }">
                  {{ index + 1 }}
                </a-avatar>
              </template>
              <template #title>
                <a-space>
                  <span>{{ item.personName }}</span>
                  <a-tag :color="getKarmaLevel(item.totalScore).color">
                    {{ getKarmaLevel(item.totalScore).level }}
                  </a-tag>
                </a-space>
              </template>
              <template #description>
                <a-space>
                  <span>总业力: {{ item.totalScore }}</span>
                  <span>善行: {{ item.goodDeeds }}</span>
                  <span>恶行: {{ item.badDeeds }}</span>
                  <span>记录数: {{ item.records.length }}</span>
                </a-space>
              </template>
            </a-list-item-meta>
          </a-list-item>
        </template>
      </a-list>
    </a-modal>

    <!-- 数据分析弹窗 -->
    <a-modal v-model:open="showStatisticsModal" title="因果业力数据分析" :width="1000" :footer="null">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-card size="small" title="善恶分布">
            <a-statistic-countdown title="善行比例" :value="(goodDeedsCount / totalKarmaCount) * 100" suffix="%" />
            <a-statistic-countdown title="恶行比例" :value="(badDeedsCount / totalKarmaCount) * 100" suffix="%" />
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card size="small" title="业力概览">
            <a-statistic title="善行总分" :value="totalGoodScore" suffix="分" />
            <a-statistic title="恶行总分" :value="totalBadScore" suffix="分" />
            <a-statistic title="净业力值" :value="totalGoodScore - totalBadScore" suffix="分" />
          </a-card>
        </a-col>
      </a-row>

      <a-divider />

      <a-row :gutter="16">
        <a-col :span="24">
          <a-card size="small" title="功能模块概览">
            <a-descriptions :column="3">
              <a-descriptions-item label="善行记录管理">
                <a-button type="link" @click="navigateToGoodDeeds"> {{ goodDeedsCount }} 条记录 → </a-button>
              </a-descriptions-item>
              <a-descriptions-item label="恶行记录管理">
                <a-button type="link" @click="navigateToBadDeeds"> {{ badDeedsCount }} 条记录 → </a-button>
              </a-descriptions-item>
              <a-descriptions-item label="业力计算引擎">
                <a-button type="link" @click="navigateToEngine"> {{ activeRulesCount }} 项规则 → </a-button>
              </a-descriptions-item>
            </a-descriptions>
          </a-card>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, UserOutlined, SmileOutlined, FrownOutlined, ThunderboltOutlined, BarChartOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { useKarmaStore } from '@/stores'

// 状态管理
const karmaStore = useKarmaStore()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const showAddModal = ref(false)
const showPersonModal = ref(false)
const showStatisticsModal = ref(false)
const editingRecord = ref(null)
const formRef = ref()
const searchQuery = ref('')
const typeFilter = ref('all')

// 表单数据
const formData = reactive({
  personName: '',
  type: 'goodDeed',
  action: '',
  description: '',
  location: '',
  witnesses: []
})

// 表单验证规则
const formRules = {
  personName: [{ required: true, message: '请输入人员姓名', trigger: 'blur' }],
  type: [{ required: true, message: '请选择行为类型', trigger: 'change' }],
  action: [{ required: true, message: '请选择具体行为', trigger: 'change' }],
  description: [{ required: true, message: '请输入行为描述', trigger: 'blur' }],
  location: [{ required: true, message: '请输入发生地点', trigger: 'blur' }]
}

// 表格列配置
const columns = [
  {
    title: '人员姓名',
    dataIndex: 'personName',
    key: 'personName',
    width: 120
  },
  {
    title: '类型',
    key: 'type',
    width: 80
  },
  {
    title: '行为',
    key: 'action',
    width: 120
  },
  {
    title: '业力值',
    key: 'score',
    width: 100,
    sorter: (a, b) => a.score - b.score
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    ellipsis: true
  },
  {
    title: '地点',
    dataIndex: 'location',
    key: 'location',
    width: 120,
    ellipsis: true
  },
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
    width: 100
  },
  {
    title: '操作',
    key: 'actions',
    width: 180,
    fixed: 'right'
  }
]

// 计算属性
const karmaRecords = computed(() => karmaStore.karmaRecords)
const totalKarmaCount = computed(() => karmaStore.totalKarmaCount)
const goodDeedsCount = computed(() => karmaStore.goodDeedsCount)
const badDeedsCount = computed(() => karmaStore.badDeedsCount)
const karmaByPerson = computed(() => karmaStore.karmaByPerson)
const karmaRules = computed(() => karmaStore.karmaRules)

// 导航相关计算属性
const totalGoodScore = computed(() => karmaRecords.value.filter((r) => r.score > 0).reduce((sum, r) => sum + r.score, 0))

const totalBadScore = computed(() => Math.abs(karmaRecords.value.filter((r) => r.score < 0).reduce((sum, r) => sum + r.score, 0)))

const activeRulesCount = computed(() => Object.keys(karmaRules.value.goodDeeds).length + Object.keys(karmaRules.value.badDeeds).length)

const pendingRetributionCount = computed(() => karmaByPerson.value.filter((person) => person.totalScore < 0).length)

// 当前选择的行为规则
const currentActionRules = computed(() => {
  return formData.type === 'goodDeed' ? karmaRules.value.goodDeeds : karmaRules.value.badDeeds
})

// 方法
const handleSearch = () => {
  // 实现搜索逻辑
  console.log('搜索:', searchQuery.value)
}

const handleFilterChange = () => {
  // 实现过滤逻辑
  console.log('过滤:', typeFilter.value)
}

const handleTypeChange = () => {
  formData.action = ''
}

const getActionName = (type, action) => {
  const rules = type === 'goodDeed' ? karmaRules.value.goodDeeds : karmaRules.value.badDeeds
  return rules[action]?.name || action
}

const getKarmaLevel = (totalScore) => {
  return karmaStore.getKarmaLevel(totalScore)
}

const viewRecord = (record) => {
  message.info('查看记录详情：' + record.description)
}

const editRecord = (record) => {
  editingRecord.value = record
  Object.assign(formData, {
    personName: record.personName,
    type: record.type,
    action: record.action,
    description: record.description,
    location: record.location,
    witnesses: record.witnesses || []
  })
  showAddModal.value = true
}

const deleteRecord = async (record) => {
  try {
    const result = await karmaStore.deleteKarmaRecord(record.id)
    if (result.success) {
      message.success('记录删除成功')
    } else {
      message.error('删除失败：' + result.error)
    }
  } catch (error) {
    message.error('删除失败：' + error.message)
  }
}

const handleSaveRecord = async () => {
  try {
    await formRef.value.validate()

    if (editingRecord.value) {
      // 编辑记录
      const result = await karmaStore.updateKarmaRecord(editingRecord.value.id, formData)
      if (result.success) {
        message.success('记录更新成功')
      } else {
        message.error('更新失败：' + result.error)
      }
    } else {
      // 新增记录
      const result = await karmaStore.addKarmaRecord(formData)
      if (result.success) {
        message.success('记录添加成功')
      } else {
        message.error('添加失败：' + result.error)
      }
    }

    handleCancelEdit()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleCancelEdit = () => {
  showAddModal.value = false
  editingRecord.value = null
  formRef.value?.resetFields()
  Object.assign(formData, {
    personName: '',
    type: 'goodDeed',
    action: '',
    description: '',
    location: '',
    witnesses: []
  })
}

// 导航方法
const navigateToGoodDeeds = () => {
  router.push('/karma/good-deeds')
}

const navigateToBadDeeds = () => {
  router.push('/karma/bad-deeds')
}

const navigateToEngine = () => {
  router.push('/karma/engine')
}

// 生命周期
onMounted(async () => {
  loading.value = true
  await karmaStore.fetchKarmaRecords()
  loading.value = false
})
</script>

<style lang="scss" scoped>
@use 'sass:color';

.karma-page {
  padding: 24px;
  min-height: 100vh;

  // 页面标题样式 - 仿照Dashboard
  .ancient-title {
    text-align: center;
    font-size: 32px;
    font-weight: bold;
    color: $secondary-color;
    margin-bottom: 48px;
    text-shadow: 0 0 20px rgba(212, 153, 10, 0.3);
  }

  // 统计卡片区域 - 仿照Dashboard风格
  .stats-row {
    margin-bottom: 48px;

    .stat-card {
      background: rgba(255, 255, 255, 0.03);
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 16px;
      padding: 24px;
      height: 120px;
      display: flex;
      align-items: center;
      justify-content: center;
      backdrop-filter: blur(10px);
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 3px;
        background: linear-gradient(90deg, transparent, $secondary-color, transparent);
        opacity: 0.6;
      }

      :deep(.ant-statistic) {
        text-align: center;

        .ant-statistic-title {
          color: $text-secondary;
          font-size: 14px;
          margin-bottom: 8px;
        }

        .ant-statistic-content {
          .ant-statistic-content-value {
            color: currentColor;
            font-weight: bold;
          }
        }
      }
    }
  }

  // 导航卡片区域 - 保持原有功能，更新样式
  .navigation-row {
    margin-bottom: 32px;

    .nav-card {
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid rgba(255, 255, 255, 0.15);
      border-radius: 16px;
      backdrop-filter: blur(10px);
      transition: all 0.3s ease;
      cursor: pointer;
      height: 100%;
      position: relative;
      overflow: hidden;

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 3px;
        opacity: 0.6;
        transition: opacity 0.3s ease;
      }

      &.good-deeds-card::before {
        background: linear-gradient(90deg, transparent, #52c41a, transparent);
      }

      &.bad-deeds-card::before {
        background: linear-gradient(90deg, transparent, #f5222d, transparent);
      }

      &.engine-card::before {
        background: linear-gradient(90deg, transparent, $primary-color, transparent);
      }

      &:hover {
        background: rgba(255, 255, 255, 0.08);
        border-color: rgba(255, 255, 255, 0.3);
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);

        &::before {
          opacity: 1;
        }
      }

      .nav-card-icon {
        height: 120px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: rgba(255, 255, 255, 0.9);

        &.good-deeds-icon {
          background: linear-gradient(135deg, rgba(82, 196, 26, 0.2), rgba(139, 195, 74, 0.2));
        }

        &.bad-deeds-icon {
          background: linear-gradient(135deg, rgba(245, 34, 45, 0.2), rgba(255, 152, 0, 0.2));
        }

        &.engine-icon {
          background: linear-gradient(135deg, rgba(114, 46, 209, 0.2), rgba(63, 81, 181, 0.2));
        }
      }

      :deep(.ant-card-meta) {
        .ant-card-meta-title {
          color: $text-primary;
          font-size: 16px;
          font-weight: 600;
        }

        .ant-card-meta-description {
          color: $text-secondary;
          font-size: 14px;
          line-height: 1.4;
        }
      }

      .nav-card-stats {
        margin-top: 16px;
        padding-top: 16px;
        border-top: 1px solid rgba(255, 255, 255, 0.1);
        color: $text-secondary;
        font-size: 12px;

        span {
          color: $text-tertiary;
        }
      }
    }
  }

  // 操作卡片和记录卡片 - 仿照Dashboard section样式
  .action-card,
  .records-card {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 16px;
    backdrop-filter: blur(10px);
    margin-bottom: 24px;

    :deep(.ant-card-head) {
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      .ant-card-head-title {
        color: $text-primary;
        font-size: 18px;
        font-weight: 600;
      }
    }

    :deep(.ant-card-body) {
      color: $text-primary;
    }
  }

  // 表格样式调整
  :deep(.ant-table) {
    background: transparent;

    .ant-table-container {
      background: transparent;
    }

    .ant-table-thead > tr > th {
      background: rgba(255, 255, 255, 0.08);
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      color: $text-primary;
    }

    .ant-table-tbody > tr > td {
      background: transparent;
      border-bottom: 1px solid rgba(255, 255, 255, 0.05);
      color: $text-secondary;
    }

    .ant-table-tbody > tr:hover > td {
      background: rgba(255, 255, 255, 0.05);
    }
  }

  // 分数值样式
  .score-value {
    font-weight: bold;

    &.positive {
      color: #52c41a;
    }

    &.negative {
      color: #f5222d;
    }
  }

  // 按钮样式调整
  :deep(.ant-btn) {
    &.ant-btn-primary {
      background: $primary-color;
      border-color: $primary-color;

      &:hover {
        background: color.adjust($primary-color, $lightness: 10%);
        border-color: color.adjust($primary-color, $lightness: 10%);
      }
    }

    &.ant-btn-link {
      color: $primary-color;

      &:hover {
        color: color.adjust($primary-color, $lightness: 10%);
      }
    }
  }

  // 输入框和选择器样式
  :deep(.ant-input),
  :deep(.ant-select-selector) {
    background: rgba(255, 255, 255, 0.08);
    border-color: rgba(255, 255, 255, 0.2);
    color: $text-primary;

    &:hover {
      border-color: $primary-color;
    }

    &:focus {
      border-color: $primary-color;
      box-shadow: 0 0 0 2px rgba(114, 46, 209, 0.2);
    }
  }

  :deep(.ant-input::placeholder) {
    color: $text-tertiary;
  }

  // 模态框样式
  :deep(.ant-modal) {
    .ant-modal-content {
      background: rgba(30, 30, 35, 0.95);
      backdrop-filter: blur(20px);
      border: 1px solid rgba(255, 255, 255, 0.15);
    }

    .ant-modal-header {
      background: transparent;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);

      .ant-modal-title {
        color: $text-primary;
      }
    }

    .ant-modal-body {
      color: $text-primary;
    }
  }

  // 列表样式
  :deep(.ant-list) {
    .ant-list-item {
      border-bottom: 1px solid rgba(255, 255, 255, 0.05);

      .ant-list-item-meta {
        .ant-list-item-meta-title {
          color: $text-primary;

          a {
            color: $text-primary;
          }
        }

        .ant-list-item-meta-description {
          color: $text-secondary;
        }
      }
    }
  }

  // 统计信息样式
  :deep(.ant-statistic-countdown) {
    .ant-statistic-content {
      color: $text-primary;
    }
  }

  // 描述列表样式
  :deep(.ant-descriptions) {
    .ant-descriptions-header {
      .ant-descriptions-title {
        color: $text-primary;
      }
    }

    .ant-descriptions-item-label {
      color: $text-secondary;
    }

    .ant-descriptions-item-content {
      color: $text-primary;
    }
  }
}

// 响应式适配
@media (max-width: 1200px) {
  .karma-page {
    .stats-row .stat-card {
      height: 100px;
      padding: 20px;
    }

    .navigation-row .nav-card .nav-card-icon {
      height: 100px;
    }
  }
}

@media (max-width: 768px) {
  .karma-page {
    padding: 16px;

    .stats-row {
      margin-bottom: 32px;

      .stat-card {
        height: 80px;
        padding: 16px;
      }
    }

    .navigation-row .nav-card .nav-card-icon {
      height: 80px;
    }
  }
}
</style>
